//
//  RepeatedPhotoViewController.swift
//  photoTool
//
//  Created by 刘清元 on 2022/8/27.
//

import UIKit
import SnapKit
import Photos
import Vision
import WCDBSwift
class RepeatedPhotoViewController: UIViewController {
        
    public var album = AlbumModel()
    private let photoSingle = PhotoSingle.shared
    private var value = 1.0
    private var listArr:[(title:String,list:[ImageModel])] = []
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        showAlert()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        missionOperationQueue.cancelAllOperations()
        missionTimer.invalidate()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        UserDefaults.standard.setValue(0, forKey: "bili")
        view.backgroundColor = .systemBackground
        let rightItem = UIBarButtonItem(title: "筛选", style: .plain, target: self, action: #selector(siftValue))
        navigationItem.rightBarButtonItem = rightItem
    }
    
    @objc func siftValue(){
        let alert = UIAlertController.init(title: "提示", message: "请输入相似值", preferredStyle: .alert)
        let actionAction = UIAlertAction(title: "确定", style: .default){ action in
            let textFile = alert.textFields?.first
            self.value = Double(textFile!.text!)!
            self.listArr = []
            self.getRepeatedData()
        }
        alert.addAction(actionAction)
        let cancelAction = UIAlertAction(title: "取消", style: .cancel)
        alert.addAction(cancelAction)
        alert.addTextField { textField in
            textField.keyboardType = .numberPad
            textField.text = "\(self.value)"
        }
        present(alert, animated: true)
    }
    
    func showAlert() {
        let alert = UIAlertController.init(title: "提示", message: "请选择需要的功能", preferredStyle: .alert)
        let cancelAction = UIAlertAction(title: "取消", style: .cancel)
        alert.addAction(cancelAction)
        let repeatAction = UIAlertAction(title: "查看已扫描重复图片", style: .default) { action in
            self.getRepeatedData()
        }
        alert.addAction(repeatAction)
        let sureAction = UIAlertAction(title: "继续扫描", style: .default) { action in
            // TODO: 开始爬取前，需要把所有爬取中的数据，重置为未爬取
            let model = ImageModel()
            model.hasContrast = 0
            try! FileTool().getDb().update(table: "image", on: ImageModel.Properties.hasContrast, with: model, where: ImageModel.Properties.hasContrast == 1)
            self.beginMission()
        }
        alert.addAction(sureAction)
        let startAction = UIAlertAction(title: "重新扫描", style: .default) { action in
            let model = ImageModel()
            model.hasContrast = 0
            try! FileTool().getDb().update(table: "image", on: ImageModel.Properties.hasContrast, with: model)
            self.beginMission()
        }
        alert.addAction(startAction)
        present(alert, animated: true)
    }
    
    func beginMission() {
        // 设置一个定时器
        missionTimer.fire()
    }

    lazy var missionTimer: Timer = {
        let timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerMission), userInfo: nil, repeats: true)
        return timer
    }()
    
    @objc func timerMission(){
        let listArr:[ImageModel] = try! FileTool().getDb().getObjects(fromTable: "image",where: ImageModel.Properties.hasContrast == 0 && ImageModel.Properties.groupName == album.albumName)
        if listArr.count > 0 {
            if missionOperationQueue.operationCount < 4 {
                alertLab.text = "当前线程数\(self.missionOperationQueue.operationCount),待对比数据是\(listArr.count)"
                let missionOperation = ImageOperation()
                missionOperation.albumName = album.albumName
                self.missionOperationQueue.addOperation(missionOperation)

            }
        }else{
            missionTimer.invalidate()
            getRepeatedData()
        }
    }
    
    lazy var missionOperationQueue: OperationQueue = {
        let queue = OperationQueue()
        queue.maxConcurrentOperationCount = 4
        return queue
    }()
    
    // 从数据库中读取重复的图片
    func getRepeatedData() {
        let array:[RepeatedModel] = try! FileTool().getDb().getObjects(fromTable: "repeated",where: RepeatedModel.Properties.value < value)
        for (index,item) in array.enumerated() {
            let leftImg:ImageModel? = try! FileTool().getDb().getObject(fromTable: "image",where: ImageModel.Properties.localIdentifier == item.leftImgId!)
            let rightImg:ImageModel? = try! FileTool().getDb().getObject(fromTable: "image",where: ImageModel.Properties.localIdentifier == item.rightImgId!)
            if leftImg != nil && rightImg != nil {
                let result = (title:"组\(index)",list:[leftImg!,rightImg!])
                listArr.append(result)
            }
        }
        alertLab.removeFromSuperview()
        self.collectionView.listArr = self.listArr
    }
    
    lazy var alertLab: UILabel = {
        let label = UILabel.init()
        view.addSubview(label)
        label.font = .systemFont(ofSize: 20)
        label.textAlignment = .center
        label.snp.makeConstraints { make in
            make.centerX.centerY.equalToSuperview()
        }
        return label
    }()
    
    lazy var collectionView: ImageListCollectionView = {
        let layout = UICollectionViewFlowLayout.init()
        let collect = ImageListCollectionView.init(frame: CGRect(x: 0, y: 0, width: screenW, height: screenH), collectionViewLayout: layout)
        view.addSubview(collect)
        collect.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        collect.cellItemDidSelected { indexPath in
            let fileTool = FileTool.init()
            let filePath = fileTool.getDocumentPath()
            let model = self.listArr[indexPath.section].list[indexPath.row]
            let alert = UIAlertController.init(title: "提示", message: "大小：\(model.fileSize ?? 0),宽：\(model.width ?? 0),高：\(model.height ?? 0)", preferredStyle: .alert)
            let sureAction = UIAlertAction.init(title: "删除", style: .default) { action in
                let localIdentifier = model.localIdentifier!
                PHPhotoLibrary.shared().performChanges {
                    let assetResult = PHAsset.fetchAssets(withLocalIdentifiers: [localIdentifier], options: nil)
                    PHAssetChangeRequest.deleteAssets(assetResult)
                } completionHandler: { result, error in
                    if (error != nil) {
                        print(error?.localizedDescription ?? "")
                    }else{
                        // 删除数据库数据
                        try! fileTool.getDb().delete(fromTable: "image",where: ImageModel.Properties.localIdentifier == localIdentifier)
                        // 删除本地data
//                        UserDefaults.standard.removeObject(forKey: localIdentifier)
                        _ = fileTool.deleteFileWithPath(path: filePath+"/imageData/"+localIdentifier.md5)
                        // 删除相似表数据
                        try! fileTool.getDb().delete(fromTable: "repeated",where: RepeatedModel.Properties.rightImgId == localIdentifier || RepeatedModel.Properties.leftImgId == localIdentifier)
                        DispatchQueue.main.async {
                            self.listArr.remove(at: indexPath.section)
                            self.collectionView.listArr = self.listArr
                            self.collectionView.reloadData()
                        }
                    }
                }
            }
            alert.addAction(sureAction)
            let cancelAction = UIAlertAction.init(title: "取消", style: .cancel)
            alert.addAction(cancelAction)
            self.present(alert, animated: true)
        }
        return collect
    }()
}
